<template>
  <Upload
    v-show="showBtn"
    class="upload-button"
    :beforeUpload="beforeUpload"
    :showUploadList="false"
    accept="application/json"
  >
    <a-button :class="[prefixCls]">
      <span ref="importRef">
        {{ getProps.label }}
      </span>
    </a-button>
  </Upload>
</template>

<script lang="ts" setup name="ButtomImport">
  import { onMounted, computed, ref, unref, getCurrentInstance } from 'vue';
  import { Upload } from 'ant-design-vue';

  import { useDesign } from '/@/hooks/web/useDesign';
  import { props, ButtomImportProps, ButtomImportInstance } from './typing';

  const { prefixCls } = useDesign('buttom-import');
  const prop = defineProps(props);
  const propsRef = ref<Partial<ButtomImportProps> | null>(null);
  const importRef = ref<HTMLDivElement>();
  const getProps = computed(() => {
    const opt = {
      ...unref(prop),
    };
    return opt as ButtomImportProps;
  });
  const emit = defineEmits(['register', 'beforeUpload']);

  onMounted(() => {});
  const beforeUpload = (e: File) => {
    // 通过json文件导入
    const reader = new FileReader();
    reader.readAsText(e);
    reader.onload = function () {
      emit('beforeUpload', this.result as string);
    };
    return false;
  };

  function setButtomImportProps(BImportProps: ButtomImportProps): void {
    propsRef.value = { ...(unref(propsRef) as Recordable), ...BImportProps } as Recordable;
  }

  async function importFile() {
    unref(importRef)?.click();
  }

  const methods: ButtomImportInstance = {
    setButtomImportProps,
    importFile,
  };

  const instance = getCurrentInstance();
  if (instance) {
    emit('register', methods, instance.uid);
  }
</script>
<style lang="less" scoped></style>
